package model
{
	import flash.events.SyncEvent;
	import flash.net.NetConnection;
	import flash.net.SharedObject;
	
	import org.puremvc.as3.interfaces.IProxy;
	import org.puremvc.as3.patterns.proxy.Proxy;
	
	import red5.as3.net.Connection;
	import red5.as3.net.events.ConnectionEvent;
	
	public class LoginProxy extends Proxy implements IProxy
	{
		public static const NAME:String = "LoginProxy";
		
		public static const FIRST_PLAYER_READY:String = "First Player Already There";
		public static const NO_PLAYER_PRESENT:String = "No Player There Yet";
		public static const LOGIN_OK:String = "Login OK";
		
		private var conn:Connection;
		private var nc:NetConnection;
		private var loginSO:SharedObject;
		private var uri:String;
		
		public function LoginProxy()
		{
			super(NAME);
			conn = new Connection();
			this.uri = BoardProxy.DEFAULT_RED5;
			conn.addEventListener(Connection.SUCCESS, onConnectionSuccess);
			conn.addEventListener(Connection.DISCONNECTED, onDisconnection);
			conn.setURI(this.uri);
			conn.connect();
		}
		
		public function onConnectionSuccess(e:ConnectionEvent):void{
			nc = conn.getConnection();
			loginSO = SharedObject.getRemote("loginSO", this.uri, false);
			loginSO.addEventListener(SyncEvent.SYNC, syncHandler);
			loginSO.client = this;
			loginSO.connect(nc);
		}
		
		public function onDisconnection(e:ConnectionEvent):void{
			
		}
		
		public function syncHandler(e:SyncEvent):void{
			checkOtherPlayer();
		}
		
		public function checkOtherPlayer():void{
			if (loginSO.data.firstPlayer == null){
				sendNotification(NO_PLAYER_PRESENT);
			} else{
				sendNotification(FIRST_PLAYER_READY, loginSO.data.firstPlayer);
			}
		}
		
		public function setPlayer(side:String, name:String):void{
			if (loginSO.data.firstPlayer == null){
				loginSO.data.firstPlayer == side;
				loginSO.data.firstPlayerName == name;
				sendNotification(LOGIN_OK);
			} else {
				sendNotification(FIRST_PLAYER_READY, loginSO.data.firstPlayer);
			}
		}

	}
}